import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { connect } from 'dva';
import { Form, Input, Upload, Select, Button, message } from 'antd';
import styles from './BaseView.less';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ user, loading }) => ({
  user,
  submitting: loading.effects['user/changeCurrent'],
}))
@Form.create()
class BaseView extends Component {

  state = {
    submitting: false,
    name: 'file',
    action: '/project/Upload/uploadFile',
    headers: {}
  }

  componentDidMount() {
    const token = window.localStorage.getItem('token') || ''
    this.setState({
      headers: { Authorization: `Bearer ${token}`, }
    })
    this.setBaseInfo();
  }

  handleSubmit = (e) => {
    e.preventDefault()
    const { form, dispatch } = this.props
    form.validateFields((err, payload) => {
      if (!err) {
        dispatch({
          type: 'user/changeCurrent',
          payload
        })
      }
    })
  }

  setBaseInfo = () => {
    const { user = {}, form } = this.props;
    const { currentUser = {} } = user
    Object.keys(form.getFieldsValue()).forEach(key => {
      const obj = {};
      obj[key] = currentUser[key] || null;
      form.setFieldsValue(obj);
    });
  };

  getViewDom = ref => {
    this.view = ref;
  };

  onChange = ({
    file = {},
    // fileList = []
  }) => {
    const { form, user = {}, dispatch } = this.props
    const { currentUser = {} } = user
    // if (file.status !== 'uploading') {
    //   console.log(file, fileList);
    // }
    if (file.status === 'done') {
      const { data = [] } = file.response
      form.setFieldsValue({
        avatar: data[0]
      })

      dispatch({
        type: 'user/saveCurrentUser',
        payload: Object.assign({}, currentUser, {
          avatar: data[0]
        })
      })
      message.success(`${file.name} 头像上传成功，还需要更新基本信息`);
    } else if (file.status === 'error') {
      message.error(`${file.name} file upload failed.`);
    }
  }

  // 头像组件 方便以后独立，增加裁剪之类的功能
  // showUploadList={false}
  avatarView = () => {
    const { name, action, headers } = this.state
    const uploadProps = { name, action, headers }
    const { user = {} } = this.props
    const { currentUser = {} } = user
    return (
      <Fragment>
        <div className={styles.avatar_title}>
          <FormattedMessage id="app.settings.basic.avatar" defaultMessage="Avatar" />
        </div>
        <div className={styles.avatar}>
          <img src={currentUser.avatar || 'https://via.placeholder.com/150'} alt="avatar" />
        </div>
        <Upload {...uploadProps} showUploadList={false} onChange={this.onChange}>
          <div className={styles.button_view}>
            <Button icon="upload">
              <FormattedMessage id="app.settings.basic.change-avatar" defaultMessage="Change avatar" />
            </Button>
          </div>
        </Upload>
      </Fragment>
    )
  }

  render() {
    const {
      // user,
      form: { getFieldDecorator },
    } = this.props;
    const { submitting } = this.state
    return (
      <div className={styles.baseView} ref={this.getViewDom}>
        <div className={styles.left}>
          <Form layout="vertical" onSubmit={this.handleSubmit} hideRequiredMark>
            <FormItem label={formatMessage({ id: 'app.settings.basic.name' })}>
              {getFieldDecorator('name', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'app.settings.basic.name-message' }, {}),
                  },
                ],
              })(<Input disabled />)}
            </FormItem>
            <FormItem label={formatMessage({ id: 'app.settings.basic.department' })}>
              {getFieldDecorator('department', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'app.settings.basic.department-message' }, {}),
                  },
                ],
                initialValue: 'lucy',
              })(
                <Select disabled>
                  <Option value="销售">销售</Option>
                  <Option value="策划">策划</Option>
                  <Option value="美术">美术</Option>
                  <Option value="前端">前端</Option>
                  <Option value="后台">后台</Option>
                </Select>
              )}
            </FormItem>
            <FormItem label={formatMessage({ id: 'app.settings.basic.phone' })}>
              {getFieldDecorator('phone', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({ id: 'app.settings.basic.phone-message' }, {}),
                  },
                ],
              })(<Input disabled />)}
            </FormItem>
            <FormItem>
              {getFieldDecorator('avatar')(<Input type="hidden" />)}
            </FormItem>
            <Button type="primary" htmlType="submit" loading={submitting}>
              <FormattedMessage
                id="app.settings.basic.update"
                defaultMessage="Update Information"
              />
            </Button>
            <FormItem>
              <div style={{ height: 200 }} />
            </FormItem>
          </Form>
        </div>
        <div className={styles.right}>
          {this.avatarView()}
        </div>
      </div>
    );
  }
}

export default BaseView;